<script setup lang="ts">
import { computed, defineEmits, ref, watch, toRaw } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import type { VxeGridProps, VxeGridListeners } from '#/adapter/vxe-table';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { useVbenForm } from '#/adapter/form';
import { useDebounceFn } from '@vueuse/core';
import {
  getOrderDeductionInfo,
  addOrderDeduction,
  editOrderDeduction,
  approvalOrderDeduction,
  againstOrderDeduction,
  deleteOrderDeduction,
} from '#/api/orderDeduction';
import { getMerchandiserDict } from '#/api/goodsPurchaseProgress';
import { getSupplyList, getDict } from '#/api/common';

import MaterialSelectModal from './materialSelectModal.vue';
import MaterialPurchaseModal from './materialPurchaseModal.vue';

import {
  Button,
  DatePicker,
  Input,
  message,
  Switch,
  Select,
  Divider,
  Spin,
} from 'ant-design-vue';

interface RowType {
  goods_purchase_sn: string;
  goods_no: string;
  expired_price: number;
  price_bili: string;
  price: number;
  mark: string;
  reason: string;
  remark: string;
  [key: string]: any;
}

const emit = defineEmits(['fetchData']);

const RecordId = ref<number>(0);
const routerData = ref<any>({});
const formData = ref<any>({});
const isDisabled = ref(true);
const tab_value = ref('多个录入');
const keyword = ref<Record<string, string>>({
  supply_id: '',
  merchandiser: '',
});

const typeList = [
  { value: 3, label: '大货逾期扣款' },
  { value: 4, label: '物料逾期扣款' },
  { value: 1, label: '其他扣款' },
  { value: 2, label: '代卖' },
];

const sourceTypeList = [
  { value: 1, label: 'CMT' },
  { value: 2, label: 'FOB' },
];

const handleAgainstToApproval = async (type: string) => {
  try {
    if (type === 'approval') {
      await approvalOrderDeduction({ ids: [RecordId.value] });
    } else {
      await againstOrderDeduction({ ids: [RecordId.value] });
    }
    message.success('操作成功');
    emit('fetchData');
    modalApi.close();
  } catch (error) {}
};

const fetchData = async () => {
  const { row } = await getOrderDeductionInfo({ id: RecordId.value });
  formApi.setValues(row);
  formData.value = { ...row }; // 保留对旧逻辑的兼容

  Object.keys(keyword.value).forEach((key: string) => {
    if (row[key]) {
      keyword.value[key] = 'initValue:' + row[key];
    }
  });

  const updatedTableData = [
    {
      goods_purchase_sn: row.goods_purchase_sn,
      goods_no: row.goods_no,
      expired_price: row.expired_price,
      price_bili: row.price_bili,
      price: row.price,
      mark: row.mark,
      reason: row.reason,
      remark: row.remark,
      supplier_name: row.supply_name || '',
      purchase_date: row.purchase_time || '',
      sale_date: row.sale_date || '',
    },
  ];
  if (formData.value.type === 2) {
    gridApi.grid.showColumn(['sale_date']);
  }else{
    gridApi.grid.hideColumn(['sale_date']);
  }

  // 更新表格数据
  gridApi.grid.loadData(updatedTableData);
};

const initClear = async () => {
  RecordId.value = 0;
  formData.value = {};
  Object.keys(keyword.value).forEach((key: string) => {
    keyword.value[key] = '';
  });
};

const init = async () => {};

// 类型改变处理
const typeChange = (type: number) => {
  // 清空表格数据
  if (gridApi) {
    gridApi.grid.loadData([]);
  }

  if (type === 3) {
    message.warning(
      '类型为【大货逾期扣款】则会在【货品进度管理报表】体现预计扣款和实际扣款的差异',
    );
  }else if (type === 4) {
    message.warning(
      '类型为【物料逾期扣款】则会在【物料进度管理报表】体现预计扣款和实际扣款的差异',
    );
  }
  if (type === 2) {
    gridApi.grid.showColumn(['sale_date']);
  }else{
    gridApi.grid.hideColumn(['sale_date']);
  }
};

// 扣款性质改变处理
const sourceTypeChange = (type: number) => {
  if (type === 1) {
    message.warning(
      'CMT是自己生产加工，这类型的扣款单被审核后会生成小蜜蜂的扣款单，FOB是归属成品系统则不生成任何其他单据',
    );
  }
};

// 计算总价
const formDataCompu = computed(() => {
  return (gridApi.grid.getTableData().tableData || []).reduce(
    (init: number, v: RowType) => {
      return Math.round((init + Number(v.expired_price)) * 100) / 100;
    },
    0,
  );
});

// 按比例计算价格
const computedPrice = async () => {
  if (!gridApi) return;

  // const tableData = gridApi.grid.getTableData().tableData;
  const tableData = gridApi.grid.getTableData().tableData;
  if (tableData.length === 0) return;

  const totalPrice = formData.value.kk_total_price || 0;
  if (totalPrice <= 0) {
    message.warning('请先输入扣款总额');
    return;
  }

  // 计算超期预扣总数
  const totalExpiredPrice = formDataCompu.value;

  if (totalExpiredPrice <= 0) {
    message.warning('表格中没有有效的超期预扣数据');
    return;
  }

  var data = JSON.parse(JSON.stringify(tableData));
  data.forEach((element: RowType) => {
    const bili = element.expired_price / totalExpiredPrice;
    const price = Number((totalPrice * bili).toFixed(2));
    const bili_ = Number((bili * 100).toFixed(2));

    element.price = price;
    element.price_bili = bili_.toString();
  });

  // 更新表格数据
  gridApi.grid.loadData(data);

  // message.success('按比例计算完成')
};

// 批量添加采购单号
const changeToSelectMuti = async () => {
  const values = await formApi.getValues();
  if (!values.type) {
    message.warning('请先选择单据类型');
    return;
  }
  if (values.type !== 4) {
    MaterialSelectModalApi.open();
  } else {
    MaterialPurchaseModalApi.open();
  }
};

const shareData = (res: any) => {
  if (res.shareType === 'material') {
    doMaterialList(res);
  } else if (res.shareType === 'materialPurchase') {
    doMaterialPurchaseList(res);
  }
};

const doMaterialList = (res: any) => {
  if (res.list && res.list.length > 0) {
    // 获取当前表格数据
    const currentTableData = gridApi.grid.getTableData().tableData || [];

    // 将选中的采购单数据转换为扣款明细需要的格式
    // 注意：现在的数据结构是采购单的基础信息，需要调用接口获取详细的采购商品信息
    const newRows = res.list.map((item: any) => ({
      goods_purchase_sn: item.caigou_id || item.goods_purchase_sn || '',
      goods_no: item.goods_no || '', // 需要后续通过接口获取具体的货号
      expired_price: item.expired_price || 0, // 需要后续通过接口获取
      price_bili: '0',
      price: 0,
      mark: '',
      reason: '',
      remark: '',
      supplier_name: item.supply_name || '',
      purchase_date: item.purchase_time || '',
    }));

    // 合并现有数据和新数据
    const updatedTableData = [...currentTableData, ...newRows];

    // 更新表格数据
    gridApi.grid.loadData(updatedTableData);
    message.success(`成功添加 ${res.list.length} 条采购单`);
  } else {
    message.warning('未选择任何采购单');
  }
};

const doMaterialPurchaseList = (res: any) => {
  if (res.list && res.list.length > 0) {
    // 获取当前表格数据
    const currentTableData = gridApi.grid.getTableData().tableData || [];

    // 将选中的物料采购数据转换为表格需要的格式
    const newRows = res.list.map((item: any) => ({
      goods_purchase_sn: item.purchase.caigou_id || '',
      goods_no: item.materialSku?.sku_sn || '',
      expired_price: item.expired_price[0] || 0,
      price_bili: '0',
      price: 0,
      mark: '',
      reason: '',
      remark: item.remark || '',
    }));

    // 合并现有数据和新数据
    const updatedTableData = [...currentTableData, ...newRows];

    // 更新表格数据
    gridApi.grid.loadData(updatedTableData);
    message.success(`成功添加 ${res.list.length} 条物料采购单`);
  } else {
    message.warning('未选择任何物料采购单');
  }
};

// 删除表格行
const handleRowDelete = async (row: RowType) => {
  if (gridApi) {
    const currentData = gridApi.grid.getTableData().tableData;
    const index = currentData.findIndex(
      (item: any) =>
        item.goods_purchase_sn === row.goods_purchase_sn &&
        item.goods_no === row.goods_no,
    );
    if (index !== -1) {
      currentData.splice(index, 1);
      gridApi.grid.loadData(currentData);
    }
  }
};

async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    let saveData = await formApi.getValues();
    saveData.tab_value = tab_value.value;
    const tableData = gridApi.grid.getTableData().tableData;
    try {
      if (RecordId.value) {
        // 编辑模式：将表格数据直接扩展到 saveData 中
        saveData = { ...saveData, ...tableData[0] };
        await editOrderDeduction({ ...saveData, id: RecordId.value });
      } else {
        // 新增模式：使用 formData 属性
        saveData.formData = tableData;
        await addOrderDeduction(saveData);
      }
      modalApi.lock();
      message.success('保存成功');
      emit('fetchData');
      modalApi.close();
    } finally {
      modalApi.lock(false);
    }
  }
}
const fetchMerchandiserOptions = async ({
  keyword = '',
}: Record<string, any>) => {
  const { list } = await getMerchandiserDict({
    quick_search: keyword,
    page: 1,
    limit: 100,
    key: 'merchUsers',
    initKey: 'data_value',
    initValue: !keyword ? formData.value?.merchandiser : '',
    select: true,
  });

  return list.map((item: any) => ({
    label: item.data_value,
    value: item.data_value,
  }));
};
// 获取供应商选项
const fetchSupplyOptions = async ({ keyword = '' }: Record<string, any>) => {

  let quick_search = '';
  let initValue = '';
  let initKey = 'id';

  if (keyword.startsWith('initValue:')) {
    initValue = keyword.replace('initValue:', '');
  } else {
    quick_search = keyword;
  }
  const { list } = await getSupplyList({
    quick_search: quick_search,
    page: 1,
    limit: 30,
    initKey: initKey,
    initValue: initValue,
    select: true,
  });
  return list.map((item: any) => ({
    label: item.SupplyNa,
    value: item.id,
  }));
}

const handleValuesChange = (formValues: any,fieldsChanged: string[]) => {
  // console.log(formValues,fieldsChanged);
};
const [Form, formApi] = useVbenForm({
  handleValuesChange:handleValuesChange,
  commonConfig: {
    disabled: isDisabled.value,
    componentProps: {
      class: 'w-full',
    },
  },
  showDefaultActions: false,
  layout: 'horizontal',
  schema: [
    {
      component: 'Select',
      fieldName: 'type',
      label: '单据类型',
      componentProps: {
        options: typeList,
        placeholder: '请选择类型',
        onChange: typeChange,
      },
      rules: 'selectRequired',
    },
    {
      component: 'ApiSelect',
      fieldName: 'supply_id',
      label: '供应商',
      componentProps: () => ({
        api: fetchSupplyOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.supply_id = value
        }, 300),
        params: { keyword: keyword.value.supply_id || undefined },
        allowClear: true,
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          if (open) keyword.value.supply_id = ''
        },
      }),
      rules: 'selectRequired',
    },
    {
      component: 'Select',
      fieldName: 'source_type',
      label: '扣款性质',
      componentProps: {
        options: sourceTypeList,
        placeholder: '请选择扣款性质',
        onChange: sourceTypeChange,
      },
      rules: 'selectRequired',
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchMerchandiserOptions,
        };
      },
      fieldName: 'merchandiser',
      label: '跟单人',
    },
  ],
  wrapperClass: 'grid grid-cols-6',
});

const gridOptions: VxeGridProps<RowType> = {
  pagerConfig: {
    enabled: false,
  },
  columns: [
    { type: 'seq', width: 60, title: '序号' },
    { field: 'goods_purchase_sn', width: 100, title: '采购单号' },
    { field: 'goods_no', width: 120, title: '货号' },
    {
      field: 'expired_price',
      width: 100,
      visible: false,
      title: '超期预扣',
    },
    { field: 'price_bili', width: 90, visible: false, title: '打包价占比%' },
    {
      field: 'price',
      width: 120,
      title: '扣款金额/元',
      editRender: {},
      slots: { edit: 'price' },
    },

    {
      field: 'reason',
      title: '扣款事由',
      minWidth: 300,
      editRender: {},
      slots: { edit: 'reason' },
    },
    {
      field: 'sale_date',
      title: '代卖日期',
      visible:false,
      width: 120,
      editRender: {name:'CellDatePicker',props: { valueFormat: 'YYYY-MM-DD' }},
    },
    {
      field: 'mark',
      minWidth: 120,
      title: '备注',
      editRender: {},
      slots: { edit: 'mark' },
    },
    {
      field: 'remark',
      minWidth: 120,
      title: '备注2',
      editRender: {},
      slots: { edit: 'remark' },
    },
    {
      field: 'operation',
      width: 80,
      title: '操作',
      visible: false,
      slots: { default: 'operation' },
    },
  ],
  exportConfig: {},
  editConfig: {
    mode: 'cell',
    trigger: 'click',
    showStatus: true,
  },
  height: '500px',
  keepSource: true,
  data: [],
  showOverflow: false,
};

const disabledOn = async () => {
  isDisabled.value = true;
  formApi.setState({ commonConfig: { disabled: true } });
};

const disabledOff = async () => {
  isDisabled.value = false;
  formApi.setState({ commonConfig: { disabled: false } });
};

watch(isDisabled, (val) => {
  formApi.setState({ commonConfig: { disabled: val } });
});

const gridEvents: VxeGridListeners<RowType> = {
  editClosed: (res) => {
    if (res.column.field === 'price') {
      // 重新计算打包价占比
      const row = res.row;
      if (formDataCompu.value > 0) {
        const bili = row.expired_price / formDataCompu.value;
        row.price_bili = Number((bili * 100).toFixed(2)).toString();
      }
    }
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridEvents,
  gridOptions,
});

const [Modal, modalApi] = useVbenModal({
  class: 'w-5/6',
  destroyOnClose: true,
  appendToMain: true,
  fullscreen: true,
  showConfirmButton: false,
  showCancelButton: false,
  onOpened: () => {
    if (!RecordId.value) {
      gridApi.grid.showColumn(['price_bili', 'expired_price', 'operation']);
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      routerData.value = modalApi.getData<Record<string, any>>();
      initClear();
      if (routerData.value?.info?.id) {
        RecordId.value = routerData.value?.info?.id;
      }
      init();

      if (RecordId.value) {
        fetchData();
        disabledOn();
      } else {
        disabledOff();
      }
    }
  },
});

const [MaterialSelectModalComp, MaterialSelectModalApi] = useVbenModal({
  connectedComponent: MaterialSelectModal,
});

const [MaterialPurchaseModalComp, MaterialPurchaseModalApi] = useVbenModal({
  connectedComponent: MaterialPurchaseModal,
});
</script>

<template>
  <Modal title="订单扣款">
    <div class="p-4">
      <Form />
      <Divider />
      <div class="mb-2 flex items-center justify-between">
        <h3 class="text-lg font-medium">扣款明细</h3>
        <div class="flex items-center">
          <div class="mr-2">
            <Input
              v-model:value="formData.kk_total_price"
              :disabled="isDisabled"
              placeholder="请输入扣款总额"
              v-if="!RecordId"
            />
          </div>
          <Button
            :disabled="isDisabled"
            type="ghost"
            class="mr-2 bg-[#b85e23] text-white hover:opacity-75"
            @click="computedPrice()"
            v-if="!RecordId"
            >按比例计算</Button
          >
          <Button
            :disabled="isDisabled"
            type="primary"
            @click="changeToSelectMuti()"
            v-if="!RecordId"
            >添加采购单</Button
          >
        </div>
      </div>

      <Grid>
        <template #operation="{ row }">
          <Button
            :disabled="isDisabled"
            danger
            size="small"
            @click="handleRowDelete(row)"
            >删除</Button
          >
        </template>
        <template #goodsPurchaseSn="{ row }">
          <Input v-model:value="row.goods_purchase_sn" :disabled="isDisabled" />
        </template>
        <template #goodsNo="{ row }">
          <Input v-model:value="row.goods_no" :disabled="isDisabled" />
        </template>
        <template #price="{ row }">
          <Input v-model:value="row.price" :disabled="isDisabled" />
        </template>
        <template #mark="{ row }">
          <Input v-model:value="row.mark" :disabled="isDisabled" />
        </template>
        <template #remark="{ row }">
          <Input v-model:value="row.remark" :disabled="isDisabled" />
        </template>
        <template #reason="{ row }">
          <Input v-model:value="row.reason" :disabled="isDisabled" />
        </template>
      </Grid>
    </div>
    <template #prepend-footer>
      <div>
        <Button @click="modalApi.close()">取消</Button>
      </div>
      <div class="space-x-2">
        <template v-if="RecordId && isDisabled">
          <!-- <Button type="ghost" class="bg-[#f56c6c] text-white hover:opacity-75" @click="handleAgainstToApproval(formData.posted ? 'against' : 'approval')">
            {{ formData.posted ? '反审' : '审核' }}
          </Button> -->
          <Button
            type="ghost"
            v-if="!formData.posted"
            class="bg-[#f0a62f] text-[#fff] hover:opacity-75"
            @click="disabledOff()"
            >修改</Button
          >
        </template>
        <Button
          v-if="!isDisabled || !RecordId"
          type="primary"
          @click="onSubmit()"
          >保存</Button
        >
      </div>
    </template>

    <MaterialSelectModalComp @share-data="shareData" />
    <MaterialPurchaseModalComp @share-data="shareData" />
  </Modal>
</template>
